
#include "stdafx.h"
#ifdef _FAN_FAN_
#include "CodeJudge.h"
#include "Utility.h"

//CCodeJudge
CCodeJudge::CCodeJudge(LPCSTR _codeid, CheckCode_Type tp)
{
	codeid = copyStr(_codeid ? _codeid : ""); commitAnswer = nullptr; codeType = tp;
	for (intptr_t i = 0; i < CCodeAcquire::Source::Count; i++)
	{
		ansArrived[i] = proced[i] = false; ans[i] = nullptr;
	}
}

CCodeJudge::~CCodeJudge()
{
	if (codeid) HeapFree(GetProcessHeap(), 0, (LPVOID)codeid);
	if (commitAnswer) HeapFree(GetProcessHeap(), 0, (LPVOID)commitAnswer);
	for (intptr_t i = 0; i < CCodeAcquire::Source::Count; i++)
		if (ans[i]) HeapFree(GetProcessHeap(), 0, (LPVOID)ans[i]);
}

bool CCodeJudge::SetAnswer(CCodeAcquire::Source source, LPCSTR answer)
{
	if (source < 0 || source >= CCodeAcquire::Source::Count) return false;
	ansArrived[source] = true;
	if (ans[source]) HeapFree(GetProcessHeap(), 0, (LPVOID)ans[source]);
	ans[source] = answer ? copyStr(answer) : nullptr;
	return true;
}

void CCodeJudge::SetCommitAnswer(LPCSTR answer, bool iscorrect)
{
	if (commitAnswer) HeapFree(GetProcessHeap(), 0, (LPVOID)commitAnswer);
	commitAnswer = copyStr(answer ? answer : "UNKNOWN"); correct = iscorrect;
}



//CCodeJudgeArray
CCodeJudge *CCodeJudgeArray::find(LPCSTR _codeid)
{
	if (!_codeid) return nullptr;
	for (intptr_t i = 0; i < size(); i++) if (recs[i] && strcmp(recs[i]->codeid, _codeid) == 0) return recs[i];
	return nullptr;
}

CCodeJudge *CCodeJudgeArray::SetAnswer(LPCSTR _codeid, CCodeAcquire::Source source, LPCSTR answer)
{
	CCodeJudge *pJudge = find(_codeid); if (!pJudge || !pJudge->SetAnswer(source, answer)) return nullptr;
	return pJudge->CommitAnswer() ? pJudge : nullptr;
}

CCodeJudge *CCodeJudgeArray::SetCommitAnswer(LPCSTR _codeid, LPCSTR answer, bool iscorrect)
{
	CCodeJudge *pJudge = find(_codeid); if (pJudge) pJudge->SetCommitAnswer(answer, iscorrect);
	return pJudge;
}

#endif
